{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 193,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "\n",
    "# 设置全局字体，避免中文乱码\n",
    "plt.rcParams['figure.dpi'] = 300  # 提高所有图形的分辨率\n",
    "config = {\n",
    "    \"font.family\": 'serif',\n",
    "    \"font.size\": 16,\n",
    "    \"mathtext.fontset\": 'stix',\n",
    "    \"font.serif\": ['SimSun'],  # 使用宋体，前提是系统安装了该字体\n",
    "}\n",
    "plt.rcParams.update(config)  # 更新配置\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 输出列名\n",
    "print(df.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取数据\n",
    "file_path = r'D:\\桌面下载\\2024数模\\代码\\Q3\\整合后的文件.xlsx'  # 替换为你的文件路径\n",
    "df = pd.read_excel(file_path)\n",
    "df.columns = df.columns.str.strip()\n",
    "\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 分组柱状图\n",
    "df['温度分组'] = pd.cut(df['温度，℃'], bins=[20, 40, 60, 80, 100], labels=['20-40', '40-60', '60-80', '80-100'])\n",
    "grouped_data = df.groupby('温度分组')['磁芯损耗，w/m3'].mean().reset_index()\n",
    "\n",
    "# 创建图形\n",
    "plt.figure(figsize=(11, 6))\n",
    "bar_plot = sns.barplot(x='温度分组', y='磁芯损耗，w/m3', data=grouped_data, palette='Blues', width=0.6, edgecolor='black')\n",
    "\n",
    "# 添加数据标签\n",
    "for p in bar_plot.patches:\n",
    "    bar_plot.annotate(f'{p.get_height():.2f}', (p.get_x() + p.get_width() / 2., p.get_height()),\n",
    "                      ha='center', va='bottom',  color='black', fontweight='bold')\n",
    "\n",
    "# 设置图形属性\n",
    "plt.title('不同温度区间对磁芯损耗的影响')  # 设置标题字体大小\n",
    "plt.xlabel('温度区间')  # 设置x轴标题字体大小\n",
    "plt.ylabel('平均磁芯损耗 (W/m³)')  # 设置y轴标题字体大小\n",
    "plt.grid(axis='y', linestyle='--', linewidth=0.7)  # 设置网格线样式\n",
    "plt.tight_layout()  # 自动调整子图参数\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "励磁波形的独立影响"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 绘制箱线图\n",
    "plt.figure(figsize=(10, 6))\n",
    "\n",
    "# 使用 Seaborn 绘制箱线图，展示励磁波形对磁芯损耗的单独影响\n",
    "sns.boxplot(\n",
    "    x='励磁波形',\n",
    "    y='磁芯损耗，w/m3',\n",
    "    data=df,\n",
    "    palette='Set3',  # 使用调色板增强视觉效果\n",
    "    fliersize=5,  # 设置离群点大小\n",
    "    linewidth=1.2  # 设置箱线图线条宽度\n",
    ")\n",
    "\n",
    "# 设置图形属性\n",
    "plt.title('励磁波形对磁芯损耗的影响分析', fontweight='bold')\n",
    "plt.xlabel('励磁波形' )\n",
    "plt.ylabel('磁芯损耗 (W/m³)')\n",
    "plt.grid(axis='y', linestyle='--', linewidth=0.7, alpha=0.6)  # 设置y轴网格线样式\n",
    "\n",
    "plt.tight_layout()  # 自动调整子图参数\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "\n",
    "# 假设 df 是你的数据框\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用 LabelEncoder 对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 绘制条形图带误差棒\n",
    "plt.figure(figsize=(8, 5))\n",
    "\n",
    "# 使用 Seaborn 绘制条形图，并显示误差棒\n",
    "bar_plot = sns.barplot(\n",
    "    x='励磁波形',\n",
    "    y='磁芯损耗，w/m3',\n",
    "    data=df,\n",
    "    palette='coolwarm',  # 使用冷暖色调\n",
    "    capsize=0.2,  # 设置误差棒端点\n",
    "    err_kws={'linewidth': 2, 'color': 'gray'},  # 使用 err_kws 设置误差棒的参数\n",
    "    errorbar='sd'  # 显示标准差作为误差棒\n",
    ")\n",
    "\n",
    "# 设置图形属性\n",
    "plt.title('励磁波形对磁芯损耗的影响', fontweight='bold')\n",
    "plt.xlabel('励磁波形')\n",
    "plt.ylabel('平均磁芯损耗 (W/m³)')\n",
    "plt.grid(axis='y', linestyle='--', linewidth=0.7, alpha=0.6)\n",
    "\n",
    "# 添加数据标签，将标签放置在箱型图竖线的右上方\n",
    "for p in bar_plot.patches:\n",
    "    bar_plot.annotate(f'{p.get_height():.2f}', \n",
    "                      (p.get_x() + p.get_width() - 0.35, p.get_height() + 50000),  # 水平右移，竖直上移\n",
    "                      ha='left', va='center', color='black', fontweight='bold')\n",
    "\n",
    "plt.tight_layout()  # 自动调整子图参数\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "\n",
    "# 绘制小提琴图\n",
    "plt.figure(figsize=(8, 5))\n",
    "sns.violinplot(\n",
    "    x='励磁波形',\n",
    "    y='磁芯损耗，w/m3',\n",
    "    data=df,\n",
    "    palette='coolwarm',\n",
    "    inner='box',  # 显示箱线图\n",
    "    scale='width'  # 根据数据分布调整宽度\n",
    ")\n",
    "\n",
    "# 设置图形属性\n",
    "plt.title('励磁波形对磁芯损耗的影响',  fontweight='bold')\n",
    "plt.xlabel('励磁波形')\n",
    "plt.ylabel('磁芯损耗 (W/m³)')\n",
    "plt.grid(axis='y', linestyle='--', alpha=0.6)\n",
    "\n",
    "plt.tight_layout()  # 自动调整子图参数\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "磁芯材料的影响"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ptitprince as pt  # 导入ptitprince库来绘制雨云图\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 绘制雨云图\n",
    "plt.figure()\n",
    "\n",
    "# 绘制雨云图，将数据、分类、y值分别传入\n",
    "plt.RainCloud(\n",
    "    x='磁芯材料',\n",
    "    y='磁芯损耗，w/m3',\n",
    "    data=df,\n",
    "    palette='coolwarm',  # 使用冷暖色调\n",
    "    bw=0.2,  # 调整密度曲线的平滑程度\n",
    "    width_viol=0.6,  # 调整小提琴部分的宽度\n",
    "    width_box=0.3,  # 调整箱线图部分的宽度\n",
    "    box_showfliers=False,  # 不显示箱线图的离群点\n",
    "    alpha=0.7,  # 整体透明度\n",
    "    move=0.2  # 调整雨滴图的位置，使其与其他部分不重叠\n",
    ")\n",
    "\n",
    "# 设置图形属性\n",
    "plt.title('磁芯材料对磁芯损耗的影响',  fontweight='bold')\n",
    "plt.xlabel('磁芯材料')\n",
    "plt.ylabel('磁芯损耗 (W/m³)')\n",
    "plt.grid(axis='y', linestyle='--', linewidth=0.7, alpha=0.6)\n",
    "\n",
    "plt.tight_layout()  # 自动调整子图参数\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 创建山脊图\n",
    "plt.figure(figsize=(10, 4))\n",
    "\n",
    "# 使用seaborn的FacetGrid绘制山脊图\n",
    "g = sns.FacetGrid(df, row='磁芯材料', hue='磁芯材料', aspect=4, height=2, palette='coolwarm')\n",
    "\n",
    "# 绘制每个分组的密度图\n",
    "g.map(sns.kdeplot, '磁芯损耗，w/m3', fill=True, alpha=0.7, linewidth=1.5)\n",
    "\n",
    "# 调整图的布局和美化\n",
    "g.set_titles(\"{row_name}\")\n",
    "g.set(yticks=[], ylabel=\"\")\n",
    "g.despine(left=True)\n",
    "g.set_xlabels('磁芯损耗 (W/m³)')\n",
    "\n",
    "# 设置整体标题\n",
    "plt.subplots_adjust(top=0.9)\n",
    "g.fig.suptitle('磁芯材料对磁芯损耗的影响', fontweight='bold')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.patheffects as patheffects  # 导入 patheffects 模块\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 准备环形条形图数据\n",
    "materials = df['磁芯材料'].unique()\n",
    "values = df.groupby('磁芯材料')['磁芯损耗，w/m3'].mean()  # 计算每种材料的平均磁芯损耗\n",
    "\n",
    "# 环形条形图的角度和条形长度设置\n",
    "num_bars = len(materials)\n",
    "angles = np.linspace(0, 2 * np.pi, num_bars, endpoint=False).tolist()  # 环形角度\n",
    "values = list(values) + [values[0]]  # 为闭合图形添加一个值\n",
    "angles += angles[:1]  # 闭合角度\n",
    "\n",
    "# 创建环形条形图\n",
    "fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))\n",
    "\n",
    "# 设置渐变背景颜色\n",
    "ax.set_facecolor('#f0f5f9')  # 设置浅灰蓝色背景\n",
    "\n",
    "# 使用渐变配色方案\n",
    "colors = plt.cm.viridis(np.linspace(0, 1, num_bars))  # 使用Viridis配色方案\n",
    "\n",
    "# 绘制环形条形图\n",
    "bars = ax.bar(\n",
    "    angles, values, width=0.3, color=colors,\n",
    "    edgecolor='black', linewidth=1.2, alpha=0.9, zorder=3\n",
    ")\n",
    "\n",
    "# 添加条形阴影效果\n",
    "for bar in bars:\n",
    "    bar.set_path_effects([\n",
    "        plt.matplotlib.patheffects.withSimplePatchShadow(offset=(3, -3), alpha=0.3)\n",
    "    ])\n",
    "\n",
    "# 设置标签位置和风格\n",
    "ax.set_xticks(angles[:-1])\n",
    "ax.set_xticklabels(['材料' + str(i) for i in range(1, num_bars + 1)],color='black')\n",
    "\n",
    "# 美化图形\n",
    "ax.set_yticklabels([])\n",
    "ax.spines['polar'].set_visible(False)\n",
    "plt.title('磁芯材料对磁芯损耗的影响', fontweight='bold')\n",
    "\n",
    "# 设置图表的网格线样式\n",
    "ax.grid(color='gray', linestyle='--', linewidth=0.5, alpha=0.6, zorder=1)\n",
    "\n",
    "plt.tight_layout()\n",
    "\n",
    "# 显示图表\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "协同影响"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from scipy.interpolate import griddata\n",
    "from matplotlib.ticker import MaxNLocator\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "\n",
    "# 假设df已经读取和预处理完成\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形'])\n",
    "\n",
    "# 将编码0调整为1，1调整为2，2调整为3，以符合原始的分类\n",
    "df['励磁波形编码'] = df['励磁波形编码'] + 1\n",
    "\n",
    "# 准备数据\n",
    "x = df['温度，℃'].values\n",
    "y = df['励磁波形编码'].values\n",
    "z = df['磁芯损耗，w/m3'].values\n",
    "\n",
    "# 创建网格数据\n",
    "xi = np.linspace(min(x), max(x), 100)  # 增加网格点数量提高曲面分辨率\n",
    "yi = np.linspace(min(y), max(y), 100)\n",
    "xi, yi = np.meshgrid(xi, yi)\n",
    "\n",
    "# 插值数据点，生成等高线数据\n",
    "zi = griddata((x, y), z, (xi, yi), method='cubic')\n",
    "\n",
    "# 绘制3D图形\n",
    "fig = plt.figure(figsize=(14, 10))\n",
    "ax = fig.add_subplot(111, projection='3d')\n",
    "\n",
    "# 绘制曲面\n",
    "surf = ax.plot_surface(xi, yi, zi, cmap='coolwarm', edgecolor='none', alpha=0.7)\n",
    "\n",
    "# 绘制浅灰色线框\n",
    "ax.plot_wireframe(xi, yi, zi, color='lightgray', linewidth=0.7)\n",
    "\n",
    "# 设置坐标轴标签，并调整标签与轴线的距离\n",
    "ax.set_xlabel('温度 (℃)', labelpad=20)\n",
    "ax.set_ylabel('励磁波形', labelpad=20)\n",
    "ax.set_zlabel('磁芯损耗 (W/m³)', labelpad=20)\n",
    "plt.title('3D 曲面图与线框：温度、励磁波形与磁芯材料的协同影响', pad=20, fontweight='bold')\n",
    "\n",
    "# 设置 y 轴刻度为 1, 2, 3\n",
    "ax.set_yticks([1, 2, 3])\n",
    "ax.set_yticklabels(['1', '2', '3'])\n",
    "\n",
    "# 调整 X 轴和 Y 轴刻度间距\n",
    "ax.xaxis.set_major_locator(MaxNLocator(nbins=6))  # 设置X轴刻度数量\n",
    "ax.yaxis.set_major_locator(MaxNLocator(nbins=6))  # 设置Y轴刻度数量\n",
    "ax.zaxis.set_tick_params(pad=10)\n",
    "\n",
    "\n",
    "# 添加颜色条，并调整颜色条的大小和位置\n",
    "cbar = fig.colorbar(surf, shrink=0.5, aspect=5, pad=0.1)\n",
    "cbar.set_label('磁芯损耗 (W/m³)')\n",
    "\n",
    "# 调整视角以更好地观察图形\n",
    "ax.view_init(elev=30, azim=120)\n",
    "\n",
    "# 使用紧凑布局，确保图形和标签不重叠\n",
    "plt.tight_layout()\n",
    "\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "励磁波形与磁芯材料"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 编码分类变量\n",
    "le_waveform = LabelEncoder()\n",
    "le_material = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形']) + 1  # 手动调整编码为1、2、3\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 准备数据\n",
    "X, Y = np.meshgrid([1, 2, 3], df['磁芯材料编码'].unique())\n",
    "Z = np.zeros_like(X, dtype=float)\n",
    "\n",
    "# 填充Z值，表示损耗\n",
    "for i, material in enumerate(df['磁芯材料编码'].unique()):\n",
    "    for j, waveform in enumerate([1, 2, 3]):\n",
    "        loss = df[(df['励磁波形编码'] == waveform) & (df['磁芯材料编码'] == material)]['磁芯损耗，w/m3']\n",
    "        Z[i, j] = loss.mean() if not loss.empty else 0  # 避免 NaN 值\n",
    "\n",
    "# 绘制3D瓦片图\n",
    "fig = plt.figure(figsize=(14, 8))\n",
    "ax = fig.add_subplot(111, projection='3d')\n",
    "\n",
    "# 使用瓦片展示\n",
    "surf = ax.plot_surface(X, Y, Z, cmap='coolwarm', edgecolor='k', alpha=0.8)\n",
    "\n",
    "# 设置坐标轴\n",
    "ax.set_xlabel('励磁波形', labelpad=15, fontsize=12)\n",
    "ax.set_ylabel('磁芯材料', labelpad=15, fontsize=12)  # 进一步增加纵坐标标签的间距\n",
    "ax.set_zlabel('磁芯损耗 (W/m³)', labelpad=23, fontsize=12)\n",
    "ax.set_title('3D瓦片图：励磁波形与磁芯材料对磁芯损耗的协同影响')  # 调整标题的pad\n",
    "\n",
    "# 手动设置X轴和Y轴的刻度为整数\n",
    "ax.set_xticks([1, 2, 3])\n",
    "ax.set_yticks(np.arange(1, len(df['磁芯材料'].unique()) + 1))\n",
    "\n",
    "# 调整Y轴刻度与轴线的距离\n",
    "# ax.yaxis.set_tick_params(pad=5)  # 增加pad值，拉开刻度标签与轴线的距离\n",
    "ax.zaxis.set_tick_params(pad=13) \n",
    "\n",
    "# 调整视角角度以获得更好的3D显示效果\n",
    "ax.view_init(elev=20, azim=-60)\n",
    "\n",
    "# 调整颜色条的位置和大小，并靠近图形\n",
    "cbar = fig.colorbar(surf, shrink=0.6, aspect=10, pad=0.08)  # 减少pad值，靠近图形\n",
    "cbar.set_label('磁芯损耗 (W/m³)', fontsize=12)\n",
    "\n",
    "# 自动调整布局\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "温度和磁芯材料"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "\n",
    "# 假设你的 df 数据已经读取完成\n",
    "# 使用LabelEncoder对分类变量编码\n",
    "le_material = LabelEncoder()\n",
    "df['磁芯材料编码'] = le_material.fit_transform(df['磁芯材料'])\n",
    "\n",
    "# 设置3D图形\n",
    "fig = plt.figure(figsize=(16, 10))\n",
    "ax = fig.add_subplot(111, projection='3d')\n",
    "\n",
    "# 准备数据\n",
    "temperatures = df['温度，℃'].unique()\n",
    "materials = df['磁芯材料'].unique()\n",
    "# colors = plt.cm.Pastel1(np.linspace(0, 1, len(temperatures)))  # 使用柔和的Pastel1配色\n",
    "colors = plt.cm.coolwarm(np.linspace(0, 1, len(temperatures)))  # 使用 coolwarm 渐变配色\n",
    "\n",
    "\n",
    "\n",
    "# 遍历温度和材料，生成箱线图数据\n",
    "for i, temp in enumerate(temperatures):\n",
    "    for j, material in enumerate(materials):\n",
    "        subset = df[(df['温度，℃'] == temp) & (df['磁芯材料'] == material)]\n",
    "        if not subset.empty:\n",
    "            # 计算箱线图的统计数据\n",
    "            box_data = subset['磁芯损耗，w/m3']\n",
    "            quartiles = np.percentile(box_data, [25, 50, 75])\n",
    "            whisker_high = np.max(box_data[box_data <= quartiles[2] + 1.5 * (quartiles[2] - quartiles[0])])\n",
    "            whisker_low = np.min(box_data[box_data >= quartiles[0] - 1.5 * (quartiles[2] - quartiles[0])])\n",
    "            mean_value = np.mean(box_data)\n",
    "\n",
    "            # 画出箱线图的箱体和须\n",
    "            ax.bar3d(i, j, whisker_low, 0.3, 0.3, whisker_high - whisker_low, alpha=0.7, color=colors[i])\n",
    "            ax.bar3d(i, j, quartiles[0], 0.3, 0.3, quartiles[2] - quartiles[0], alpha=0.9, color=colors[i])\n",
    "            ax.scatter(i, j, quartiles[1], color='black', s=100, edgecolors='yellow', linewidth=0.6)  # 中位数点\n",
    "            ax.scatter(i, j, mean_value, color='orange', s=100, marker='x', edgecolors='red', linewidth=1)  # 均值点\n",
    "            ax.plot([i, i], [j, j], [quartiles[0], quartiles[2]], color='black', linestyle='--', linewidth=1.5)  # 四分位数线\n",
    "\n",
    "# 设置坐标轴\n",
    "ax.set_xticks(range(len(temperatures)))\n",
    "ax.set_xticklabels(temperatures, rotation=45, ha='right')  # 旋转X轴标签\n",
    "ax.set_yticks(range(len(materials)))\n",
    "ax.set_yticklabels(materials, rotation=45, ha='right')  # 旋转Y轴标签\n",
    "ax.set_zlabel('磁芯损耗 (W/m³)', labelpad=27)  # 增加Z轴标签的距离\n",
    "\n",
    "# 设置X轴和Y轴的标签距离\n",
    "ax.set_xlabel('温度 (℃)', labelpad=30)  # 增加X轴标签的距离\n",
    "ax.set_ylabel('磁芯材料', labelpad=30)  # 增加Y轴标签的距离\n",
    "\n",
    "ax.zaxis.set_tick_params(pad=13)\n",
    "\n",
    "plt.title('3D箱线图：温度与磁芯材料对磁芯损耗的协同影响', fontweight='bold', pad=20)\n",
    "\n",
    "# 添加颜色条\n",
    "# sm = plt.cm.ScalarMappable(cmap=plt.cm.Pastel1, norm=plt.Normalize(vmin=min(temperatures), vmax=max(temperatures)))\n",
    "sm = plt.cm.ScalarMappable(cmap=plt.cm.coolwarm, norm=plt.Normalize(vmin=min(temperatures), vmax=max(temperatures)))\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "sm.set_array([])\n",
    "cbar = plt.colorbar(sm, ax=ax, shrink=0.6, aspect=10, pad=0.1)\n",
    "cbar.set_label('温度 (℃)')\n",
    "\n",
    "# 优化视角\n",
    "ax.view_init(elev=30, azim=120)  # 调整视角，避免遮挡和重叠\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "温度和励磁波形"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "\n",
    "# 数据预处理\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "le_waveform = LabelEncoder()\n",
    "df['励磁波形编码'] = le_waveform.fit_transform(df['励磁波形']) + 1  # 确保编码为 1, 2, 3\n",
    "\n",
    "# 绘制3D散点图\n",
    "fig = plt.figure(figsize=(14, 10))\n",
    "ax = fig.add_subplot(111, projection='3d')\n",
    "\n",
    "# 使用coolwarm颜色映射\n",
    "temperatures = df['温度，℃']\n",
    "norm = plt.Normalize(vmin=temperatures.min(), vmax=temperatures.max())\n",
    "sm = plt.cm.ScalarMappable(cmap=plt.cm.coolwarm, norm=norm)\n",
    "\n",
    "# 绘制散点图，颜色根据温度变化\n",
    "scatter = ax.scatter(df['温度，℃'], df['励磁波形编码'], df['磁芯损耗，w/m3'],\n",
    "                     c=temperatures, cmap='coolwarm', s=80, alpha=0.8)\n",
    "\n",
    "# 设置坐标轴标签并调整位置\n",
    "ax.set_xlabel('温度 (℃)', labelpad=15)  # 调整X轴标签与轴线的距离\n",
    "ax.set_ylabel('励磁波形', labelpad=45)  # 调整Y轴标签与轴线的距离\n",
    "ax.set_zlabel('磁芯损耗 (W/m³)', labelpad=18)  # 调整Z轴标签与轴线的距离\n",
    "plt.title('3D 散点图：温度与励磁波形对磁芯损耗的影响', fontweight='bold')\n",
    "\n",
    "# 设置 y 轴刻度和标签\n",
    "ax.set_yticks([1, 2, 3])\n",
    "ax.set_yticklabels(['励磁波形1', '励磁波形2', '励磁波形3'], fontsize=14)  # 自定义Y轴标签\n",
    "\n",
    "# 设置 y 轴刻度与轴线之间的距离\n",
    "ax.yaxis.set_tick_params(pad=22)  # 调整Y轴刻度标签与轴线的距离\n",
    "ax.zaxis.set_tick_params(pad=10)\n",
    "# 调整颜色条的位置、大小和标签\n",
    "cbar = fig.colorbar(sm, shrink=0.6, aspect=10, pad=0.1)  # 调整颜色条的缩放和与图形的距离\n",
    "cbar.set_label('温度 (℃)')  # 使用温度作为颜色条的标签\n",
    "\n",
    "# 调整视角以优化显示效果\n",
    "ax.view_init(elev=30, azim=120)  # elev 是仰角，azim 是方位角\n",
    "\n",
    "# 使用紧凑布局\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py38torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
